import { indexData, dayRecommendCookbookList, subscribeMessage, hadSubscribe } from "../../api/tyg"
const { requestSubscribeMessage } = requirePlugin('subscribeMsg');

Page({
  data: {
    cookbookList: [],
    history: [],
    slider: [],
    eleConfig: [],
    tplmsgId: [],
    hadSubscribe: false
  },
  onLoad() {
    var that = this;
    that.getIndexData()
    that.hadSubscribe();
    that.getData();
    that.getHistory();
  },
  getIndexData(){
    var that = this;
    indexData().then(res => {
        console.log(res);
        that.setData({
          slider: res.data.slider,
          eleConfig: res.data.eleConfig,
          tplmsgId: res.data.tplmsgId,
        })
    })
  },
  hadSubscribe(){
    var that = this;
    my.getAuthCode({
      scopes: 'auth_base', // 主动授权：auth_user，静默授权：auth_base。或者其它scope
      success: (res) => {
        if (res.authCode) {
          // 认证成功
          // 调用自己的服务端接口，让服务端进行后端的授权认证，并且利用session，需要解决跨域问题
          hadSubscribe(res.authCode).then(res => {
              console.log(res);
              that.setData({
                hadSubscribe: res.data.hadSubscribe,
              })
          })
        }
      },
    });
    
  },
  getHistory(){    
    var that = this;
    my.getStorage({
      key: 'history',
      success: (result) => {
        this.setData({
          'history': result.data
        });
      }
    });
  },
  getData(){
    var that = this;
    dayRecommendCookbookList().then(res => {
      console.log(res)
      let data = res.data.list;
      that.setData({
        cookbookList: data
      })
    })
  },
  onEnterDetail: function (event) {
    var id = event.currentTarget.dataset.id;
    my.navigateTo({
      url: '/pages/detail/detail?id=' + id
    });
  },
  onGoSearch: function () {
    my.navigateTo({
      url: '/pages/search/search'
    });
  },
  enterArticle: function(){
    my.navigateTo({
      url: '/pages/article/article'
    });
  },
  onLabelSearch: function (event) {
    var search = event.currentTarget.dataset.value;
    my.navigateTo({
      url: '/pages/list/list?search=' + search
    });
  },
  enterNcov: function(){
    my.navigateToMiniProgram({
      appId: '2021001132600368',
    });
  },
  onTkcoupon: function(){
    my.navigateToMiniProgram({
      appId: '2021001157608051'
    });
  },
  onBuy: function(){
    my.navigateTo({
      url: '/pages/buy/buy'
    });
  },
  onHotbag: function(){
    my.navigateToMiniProgram({
      appId: '2021001156606867',
      path: 'pages/buy/buy',
    });
  },
  onYitao(e){
    my.navigateToMiniProgram({
     appId: '2018091261350219',//收藏有礼小程序的appid，固定值请勿修改
     path: '/pages/h5pages/h5pages?targetURI=https://mo.m.taobao.com/etao/tmpl_mini_butie_b?pid=mm_1210180140_1782900400_110684150201&union_lens=lensId%3APUB%401595311117%400baf7c5e_0fc4_1736ff3d6ab_05c0%4001'
    });
  },
  onEle(e){
    var that = this;
    let index = e.currentTarget.dataset.index;
    let link = that.data.eleConfig[index]['link'];
    my.loadPlugin({
      plugin: '3000000027034925@*', 
      success() {
        my.navigateTo({
          url: `dynamic-plugin://3000000027034925/index?page_url=${link}`, // 商业授权插件
        });
      }
    })
  },
  onTypePage(e){
    var that = this;
    let index = e.currentTarget.dataset.index;
    let type = that.data.slider[index]['type'];
    let link = that.data.slider[index]['link'];
    if(type == 'yitao'){
      my.navigateToMiniProgram({
        appId: '2018090761255717',//收藏有礼小程序的appid，固定值请勿修改
        path: 'pages/webview-redirect/webview-redirect?url=https://mo.m.taobao.com/etao/tmpl_mini_butie_b?pid=mm_1210180140_1782900400_110684150201&union_lens=lensId%3APUB%401595311117%400baf7c5e_0fc4_1736ff3d6ab_05c0%4001'
      });
    }
    if(type == 'taobao'){
      my.loadPlugin({
        plugin: '3000000027034925@*', 
        success() {
          my.navigateTo({
            url: `dynamic-plugin://3000000027034925/index?page_url=${link}`, // 商业授权插件
          });
        }
      })
    }
    if(type == 'ele'){
      my.navigateToMiniProgram({
        appId: '2018090761255717',
        path:'pages/webview-redirect/webview-redirect?url=' + link
      });
    }
    if(type == 'page'){
      my.navigateToMiniProgram({
        appId: '2021001157608051',
        path: link
      });
    }
    if(type == 'miniProgram'){
      my.navigateToMiniProgram({
        appId: link,
      });
    }
  },
  subscribeMessage(){
    var that = this;
    let templateList = that.data.tplmsgId;
    requestSubscribeMessage({
      // 模板id列表，最多3个
      entityIds: templateList,
      // 接收结果的回调方法
      callback(res) {
        console.log('订阅回调', res);
        if (res.success) {
          const successIds = templateList
            .filter(i => res[i] === 'accept')
            .map(i => i);

          console.log(successIds);
          my.getAuthCode({
            scopes: 'auth_base', // 主动授权：auth_user，静默授权：auth_base。或者其它scope
            success: (res) => {
              if (res.authCode) {
                // 认证成功
                // 调用自己的服务端接口，让服务端进行后端的授权认证，并且利用session，需要解决跨域问题
                subscribeMessage(successIds.join(','), res.authCode).then(res => {
                  // 订阅成功
                  my.call('toast', {
                    content: `订阅成功`,
                    type: 'success',
                  });
                  that.setData({
                    hadSubscribe: true,
                  })
                }).catch(err => {
                  my.showToast({
                    content: err.msg
                  })
                })
              }
            },
          });
        }
      },
    });
  },
});
